package com.lixixi.tingshu.user.api;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.lixixi.tingshu.common.anno.NeedLogin;
import com.lixixi.tingshu.common.result.Result;
import com.lixixi.tingshu.common.util.AuthContextHolder;
import com.lixixi.tingshu.model.user.UserInfo;
import com.lixixi.tingshu.user.service.WxMiniAppService;
import com.lixixi.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@RestController
@RequestMapping("/api/user/wxLogin")
public class UserWxLoginApiController {

	@Autowired
	WxMiniAppService wxMiniAppService;

	@GetMapping("/wxLogin/{js_code}")
	public Result<JSONObject> wxLogin(@PathVariable("js_code") String jsCode) throws WxErrorException {
		JSONObject jsonObject = wxMiniAppService.wxLogin(jsCode);
		return Result.ok(jsonObject);
	}

	@GetMapping("/getUserInfo")
	@NeedLogin
	public Result<UserInfoVo> getUserInfo() {
		Long userId = AuthContextHolder.getUserId();
		UserInfo userInfo = wxMiniAppService.getById(userId);
		return Result.ok(BeanUtil.toBean(userInfo, UserInfoVo.class));
	}

	@GetMapping("/getUserInfo/forFeign")
	public Result<UserInfoVo> getUserInfoForFeign(@RequestParam("userId") Long userId){
		UserInfo userInfo = wxMiniAppService.getById(userId);
		return Result.ok(BeanUtil.toBean(userInfo, UserInfoVo.class));
	}

	@PostMapping("/updateUser")
	@NeedLogin
	public Result updateUser(@RequestBody UserInfoVo userInfoVo){
		wxMiniAppService.updateUser(userInfoVo);
		return Result.ok();
	}

	@GetMapping("/test2")
	public String getToken(){
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		return request.getHeader("token");
	}

}
